/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package web.services;

import java.util.ArrayList;
import java.util.Collection;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import se392.ateam2006.authentication.GroupEntity;
import se392.ateam2006.user.UserEntity;
import web.util.BusinessFacadeDelegate;

/**
 *
 * @author Caroline
 */
public class AdminService extends GenericService {

    public String executePreDispatch(HttpServletRequest request, ServletContext context) throws Exception {
        BusinessFacadeDelegate delegate = this.getDelegate(request.getSession());
        HttpSession session = request.getSession();
        Collection<GroupEntity> groupList = delegate.getAllGroups();
        Collection<String> groupNames = new ArrayList<String>();
        for(GroupEntity group: groupList) {
            groupNames.add(group.getGroupid());
        }
        session.setAttribute("groupList", groupNames);
        
        String task = request.getPathInfo();
        if(task.contains("/admin/AddUser")) {
            String email = request.getParameter(ADMIN_EMAIL);
            String firstName = request.getParameter(ADMIN_FIRST_NAME);
            String surname = request.getParameter(ADMIN_SURNAME);
            String password = request.getParameter(ADMIN_PASSWORD);
            
            UserEntity user = new UserEntity(email, firstName, surname);
            user.setPassword(password);
            delegate.createUser(user);            
        }
        if(task.contains("/admin/AddGroup")) {
            String groupId = request.getParameter(ADMIN_GROUP_ID);
            GroupEntity group = new GroupEntity(groupId);
            delegate.addGroup(group);
        }
        
        if(task.contains("/admin/UserGroup")) {
            String email = request.getParameter(ADMIN_GROUP_EMAIL);
            UserEntity user = delegate.getUser(email);
            String groupId = request.getParameter(ADMIN_GROUP_TO_ADD);
            GroupEntity group = delegate.getGroup(groupId);
            delegate.addUserToGroup(user, group);
        }
        return "user";
    }

    public void executePostDispatch(HttpServletRequest request, ServletContext context) throws Exception {
        
    }

}

